import store from "@/store/store";

/**
 * 判断是否登录
 */
export const isLogin = (): boolean => {
  return !(
    Object.keys(store().userInfo).length === 0 || isNull(store().userInfo.id)
  );
};

export const setToken = (token: string) => {
  localStorage.setItem("access_token", token);
};

export const getToken = () => {
  return window.localStorage.getItem("access_token");
};

export const removeToken = () => {
  window.localStorage.removeItem("access_token");
};

export const getBackImg = (imageUrl: string) => {
  return "url(&#34;" + imageUrl + "&#34;)";
};

/**
 * 获取指定名称的cookie
 * @param name
 */
export const getCookie = (name: string): string => {
  let allCookie = document.cookie; //获取cookie字符串
  console.log(allCookie);
  let arrCookie = allCookie.split("; "); //分割
  //遍历匹配
  for (let i = 0; i < arrCookie.length; i++) {
    let arr = arrCookie[i].split("=");
    console.log(arr[0] + " : " + arr[1]);
    if (arr[0] === name) {
      return arr[1];
    }
  }
  return "";
};

/**
 * 判断数据是否存在、合法
 * @param val
 */
export const isNull = (val: any): boolean => {
  if (val === null || val === undefined) {
    return true;
  }
  if (typeof val === "string") {
    return val.trim() === "";
  }
  if (typeof val === "number") {
    // NaN是唯一个不等于自身的值
    return val !== val;
  }
  return false;
};

/**
 * 全局loading
 * 使用close()关闭
 * @returns
 */
export const loading = () => {
  return ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(255, 255, 255, 0.5)",
  });
};

/**
 * 错误提示
 * @param msg
 */
export const errorNotify = (msg: string): void => {
  ElNotification({
    type: "error",
    title: msg,
  });
};
/**
 * 警告
 * @param msg
 */
export const warnNotify = (msg: string) => {
  ElNotification({
    type: "warning",
    title: msg,
  });
};
/**
 * 成功提示
 * @param msg
 */
export const successNotify = (msg: string) => {
  ElNotification({
    type: "success",
    title: msg,
  });
};

/**
 * 返回用户名
 * @param userName
 * @param userId
 */
export const userName = (userName: string, userId: string): string => {
  return isNull(userName) ? "ali_" + userId : userName;
};

/**
 * 数字转换，防止数字过长，用于播放量，弹幕量，点赞量。。。
 * @param num
 */
export const numberConversion = (num: number): string => {
  if (isNull(num)) {
    return "0";
  }
  if (num < 10000) {
    return num + "";
  } else if (num >= 10000 && num < 100000000) {
    return (num / 10000).toFixed(1) + "万";
  } else {
    return (num / 100000000).toFixed(1) + "亿";
  }
};

/**
 * 时间转换：秒 --> 时分秒
 * @param time
 */
export const timeConversion = (time: number): string => {
  time = Math.floor(time);
  let sec = ((time % 60) + "").padStart(2, "0");
  let min = ((Math.floor(time / 60) % 60) + "").padStart(2, "0");
  let hour = Math.floor(time / 3600);
  let tm = `${min}:${sec}`;

  return hour > 0 ? `${hour}:${tm}` : tm;
};

/**
 * 日期转换：
 * 当date为今天 --> 时分秒
 * date为今年 --> 月日
 * else --> 年月日
 * @param date yyyy-MM-dd HH:mm:ss
 */
export const dateConversion = (date: string): string => {
  if (isNull(date)) {
    return "";
  }

  date = date + "";
  let dateTime = date.split(" ");

  // 若date是今天，则返回时分秒
  if (dateTime[0] === getNowDate()) return dateTime[1];

  let tmpDate = dateTime[0].split("-");
  // 去掉月日前面可能存在的0
  for (let i = 0; i < tmpDate.length; i++) {
    tmpDate[i] =
      tmpDate[i].charAt(0) === "0" ? tmpDate[i].substring(1) : tmpDate[i];
  }

  // 若date为今年，则返回月日；否则返回年月日
  return tmpDate[0] == new Date().getFullYear().toFixed()
    ? `${tmpDate[1]}-${tmpDate[2]}`
    : dateTime[0];
};

/**
 * 获取当前年月日 yyyy-MM-dd
 */
export const getNowDate = (): string => {
  let date = new Date(),
    year = date.getFullYear(),
    month = date.getMonth() + 1,
    strDate = date.getDate();

  return (
    year +
    "-" +
    String(month).padStart(2, "0") +
    "-" +
    String(strDate).padStart(2, "0")
  );
};
